package org.jetlinks.pro.tenant.term;

import org.hswebframework.ezorm.core.param.Term;
import org.hswebframework.ezorm.rdb.metadata.RDBColumnMetadata;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.PrepareSqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.SqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.term.AbstractTermFragmentBuilder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class TenantMemberTermBuilder extends AbstractTermFragmentBuilder {

    public static final String ID = "member";

    public TenantMemberTermBuilder() {
        super(ID, "租户用户关联数据");
    }

    @Override
    public SqlFragments createFragments(String columnFullName, RDBColumnMetadata column, Term term) {

        PrepareSqlFragments sqlFragments = PrepareSqlFragments.of();

        if (term.getOptions().contains("not")) {
            sqlFragments.addSql("not");
        }
        sqlFragments.addSql("exists(select 1 from s_tenant_member tm where tm.user_id = ", columnFullName);
        if (!term.getOptions().contains("any")) {
            List<Object> tenants = convertList(column, term);
            sqlFragments.addSql("and tm.tenant_id in (")
                        .addSql(tenants.stream().map(id -> "?").collect(Collectors.joining(",")))
                        .addSql(")")
                        .addParameter(tenants);
        }
        sqlFragments.addSql(")");

        return sqlFragments;
    }
}
